const { ListToNode, NodeToList, ListNode, timeL } = require("../utils.js");
/**
 * @param {number[]} candidates
 * @param {number} target
 * @return {number[][]}
 */
var combinationSum2 = function (candidates, target) {
  let res = {};
  let map = {};
  for (let i = 0; i < candidates.length; i++) {
    map[candidates[i]] = map[candidates[i]] || 0;
    map[candidates[i]] += 1;
  }

  const fun = (map, target, arr = []) => {
    for (let i in map) {
      let key = +i;
      if (key === target) {
        let keys = [...arr, key].sort((a, b) => a - b).join("-");
        if (!res[keys]) res[keys] = true;
      } else if (key < target) {
        let obj = { ...map };
        if (obj[i] === 1) delete obj[i];
        else obj[i] -= 1;
        fun(obj, target - key, [...arr, key]);
      }
    }
  };
  fun(map, target);
  return Object.keys(res).map((item) => {
    return item.split("-").map((item) => +item);
  });
};
// let candidates = [10, 1, 2, 7, 6, 1, 5],
//   target = 8;
let candidates = [
  1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1,
];
target = 27;

timeL(combinationSum2, [candidates, target]);
